package com.iliad2x.FlexTransform.uiObject
{
	import com.iliad2x.FlexTransform.uiObject.SelectionObject;
	
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	import mx.core.UIComponent;
	
	import spark.components.Group;
	
	import com.iliad2x.FlexTransform.config.GlobalDatas;

	public class TransformItem extends Group
	{
		private var _bg:Shape = new Shape;
		private var _targetObject:UIComponent;
		
		public function TransformItem()
		{
			addEvents();
			makeBackground();
		}
		
		/** Add Object for Transform-Item **/
		public function addObject($value:UIComponent):void
		{
			if(_targetObject)
				removeElement(_targetObject);
			
			addElement($value);
			
			_targetObject = $value;
			_targetObject.x = GlobalDatas.anchorSize;
			_targetObject.y = GlobalDatas.anchorSize;
			
			resizeBackground(_targetObject.width, _targetObject.height);
		}
		
		/** Make Background for TransformItem **/
		private function makeBackground():void
		{
			var bg:UIComponent = new UIComponent;
			addElement(bg);
			
			var sprite:Sprite = new Sprite;
			bg.addChild(sprite);
			
			sprite.addChild(_bg);
		}
		
		/** Resize Background Shape **/
		private function resizeBackground($width:Number, $height:Number):void
		{
			_bg.graphics.clear();
			_bg.graphics.beginFill(0x000000, 1);
			_bg.graphics.drawRect(0, 0, $width + (GlobalDatas.anchorSize*2), $height+(GlobalDatas.anchorSize*2));
			_bg.graphics.endFill();
			
			trace("resizeBackground = ", $width, $height);
			
			this.width = _bg.width;
			this.height = _bg.height;
		}
		
		/** Select Object for Selected-Object **/
		private function selectObject($target:UIComponent):void
		{
			var sobj:SelectionObject = new SelectionObject;
			sobj.targetObject = _targetObject;
			addElement(sobj);
		}
		
		/** Add Events for TransformItem **/
		private function addEvents():void
		{
			addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
		}
		
		/** Mouse-Down EventHandler fot Added-Child-Object **/
		private function onMouseUpHandler(e:MouseEvent):void
		{
			var obj:UIComponent = e.currentTarget as UIComponent;
			
			if( obj )
			{
				trace("Item selected = ", obj.x, obj.y, obj.width, obj.height);
				selectObject(obj);
			}
		}
		
	}
}